<template>
  <div id="wghlarge">
    <!--头部-->
    <div class="topheader">
      <div class="head01">
        <div class="head01-1">
          <div class="head01-2" style="min-width: 470px;"><div class="appname">指挥调度</div> <span class="split">|</span><span class="place">{{currentAreaName}}</span></div>
        </div>
        <div class="head01-3" v-if="userCode != 2">
          <div class="myselect" id="mySelect" @click="showTownSelector=!showTownSelector">
            <span>切换区域</span>
          </div>
          <transition :duration="500" enter-active-class="animated fadeInUp2" leave-active-class="animated fadeOut">
            <div class="town-selector" v-show="showTownSelector">
              <div class="towns" v-for="(item, index) in towns" :key="index" :class="{active: item.active}" @click="handlerAreaChange(item, index)">{{item.spaceName}}</div>
            </div>
          </transition>
        </div>
        <!-- <div class="topbtns">
          <div class="head01-4" @click="showSphs=!showSphs"><span>视频会商</span></div>
        </div> -->
        <div class="backIcon" @click="backIconClick"></div>
      </div>
    </div>
    <!--地图-->
    <div id="map-container"></div>
    <div class="time-selector" v-show="currentActiveOptionIndex == 4">
      <TimeSlider ref="timeSlider" @change="sliderChanged"/>
      <div class="audioControl">
        <div><i class="iconfont icon-arrow-" @click="handlerMarkerMove(1)"></i></div>
         <div><i class="iconfont icon-kuaitui" @click="handlerMarkerMove(3)"></i></div>
          <div><i class="iconfont icon-kuaijin" @click="handlerMarkerMove(2)"></i></div>
        <div><i class="iconfont icon-tingzhi" @click="handlerMarkerMove(0)"></i></div>
      </div>
      <div class="speedBar">
        <span>速度</span>
        <el-slider :min="500" class="bar" v-model="pathSpeed" show-stops :max="6000" @change="speedChanged"/>
      </div>
      <div class="qzbl-checkbox">
        <el-checkbox v-model="qzbl.qz" @change="sliderChanged">去噪</el-checkbox>
        <el-checkbox v-model="qzbl.bl" @change="sliderChanged">绑路</el-checkbox>
      </div>
    </div>
    <div class="element-checkbox">
      <el-checkbox v-model="showGrids" @change="handlerElCheckBox(showGrids, 'showGrids')" >显示网格</el-checkbox>
      <el-checkbox v-model="showAllPerson" v-show="currentActiveOptionIndex == 4" @change="handlerElCheckBox(showAllPerson, 'showAllPerson')" >显示人员</el-checkbox>
    </div>
     <!-- 实时感知-->
    <div id="xkSsgz">
      <div class="title">实时动态</div>
      <div class="selector">
        <div class="item _l curpointer" :class="{active: ssdtChartTab == '网格员'}" @click="showKqInfo('网格员')">网格员</div>
        <div class="item _r curpointer" :class="{active: ssdtChartTab == '执法队员'}" @click="showKqInfo('执法队员')"><div>执法队员</div></div>
      </div>
      <div class="number-items">
        <div v-show="ssdtChartTab == '执法队员'">
          <div class="item2"><div>
            <div class="name">今日案件量</div>
            <div class="count"><div class="num"><animated-number :value="tongjiInfo.zfy.todayCount" :duration="800" :formatValue="$Filter.engNumberFmt"  :round="1"/></div><div class="dw">件</div></div>
          </div></div>
          <div class="item2 _12"><div>
            <div class="name">累计案件量</div>
            <div class="count"><div class="num"><animated-number :value="tongjiInfo.zfy.totalCount" :duration="800" :formatValue="$Filter.engNumberFmt"  :round="1"/></div><div class="dw">件</div></div>
          </div>
        </div></div>
        <div v-show="ssdtChartTab == '网格员'">
          <div class="item2 _21"><div>
            <div class="name">今日事件量</div>
            <div class="count"><div class="num"><animated-number :value="tongjiInfo.wgy.todayCount" :duration="800" :formatValue="$Filter.engNumberFmt"  :round="1"/></div><div class="dw">件</div></div>
          </div></div>
          <div class="item2 _12"><div>
            <div class="name">当月事件量</div>
            <div class="count"><div class="num"><animated-number :value="tongjiInfo.wgy.totalCount" :duration="800" :formatValue="$Filter.engNumberFmt"  :round="1"/></div><div class="dw">件</div></div>
          </div></div>
        </div>
      </div>
      <!-- <div class="subtitle"><span>今日考勤</span></div>
      <div v-show="ssdtChartTab == '网格员'">
        <div id="chartJrkq" style="width:280px;height:200px;"></div>
        <div class="persons">
          <div class="item"><div class="num">{{kqInfo.wgy.zc}}</div></div>
          <div class="item"><div class="num">{{kqInfo.wgy.qq}}</div></div>
          <div class="item"><div class="num">{{kqInfo.wgy.yc}}</div></div>
        </div>
      </div> -->
      <!-- <div v-show="ssdtChartTab == '执法队员'">
        <div id="chartJrkqZfdy" style="width:280px;height:200px;"></div>
        <div class="persons">
          <div class="item"><div class="num">{{kqInfo.zfdy.zc}}</div></div>
          <div class="item"><div class="num">{{kqInfo.zfdy.qq}}</div></div>
          <div class="item"><div class="num">{{kqInfo.zfdy.yc}}</div></div>
        </div>
      </div> -->
      <div class="subtitle" style="margin-top:8px;"><span>{{ssdtChartTab == '执法队员' ? '案件' : '事件'}}处理</span></div>
        <div id="sjcl">
          <div class="leftItems" v-show="ssdtChartTab == '网格员'">
            <div class="item">
              <div class="l1">待处理</div>
              <div class="r1"><animated-number :value="tongjiInfo.wgy.dclCount" :duration="800" :round="1"/></div>
            </div>
            <div class="item">
              <div class="l1">处理中</div>
              <div class="r1"><animated-number :value="tongjiInfo.wgy.clzCount" :duration="800" :round="1"/></div>
            </div>
            <div class="item">
              <div class="l1">已办结</div>
              <div class="r1"><animated-number :value="tongjiInfo.wgy.ybjCount" :duration="800" :round="1"/></div>
            </div>
          </div>
          <div class="leftItems" v-show="ssdtChartTab == '执法队员'">
            <div class="item">
              <div class="l1">处理中</div>
              <div class="r1"><animated-number :value="tongjiInfo.zfy.clzCount" :duration="800" :round="1"/></div>
            </div>
            <div class="item">
              <div class="l1">已办结</div>
              <div class="r1"><animated-number :value="tongjiInfo.zfy.yclCount" :duration="800" :round="1"/></div>
            </div>
          </div>
          <div class="right">
            <div class="rightItem">
              <BeautyBall style="margin:0 auto;" :range="ssdtChartTab == '执法队员' ? tongjiInfo.zfy.lv : (tongjiInfo.wgy.lv || 0)"/>
              <div class="bjl">办结率</div>
            </div>
            <div class="rltBtn" :class="{active: showRlt}" @click="handlerRltbtnClick" style="display:none;"></div>
          </div>
        </div>
    </div>
    <!-- 事件列表-->
    <div id="xkSjlb">
      <div class="leftFrame" v-loading="optionList[0].active && optionList[0].loading" v-show="!showRightDetail">
        <div class="optionBar">
          <!-- <div class="item" v-for="(item, index) in optionList" :key="index" :class="{active: item.active}" @click="handlerListOption(index)">{{item.name}}</div> -->
          <div class="item" v-for="(item, index) in optionList.slice(0, 1)" :key="'a' + index" :class="{active: item.active}" @click="handlerListOption(0)">{{item.name}}</div>
          <!-- <div class="item" v-for="(item, index) in optionList.slice(1, 2)" :key="'d' + index" :class="{active: item.active}" @click="handlerListOption(1)">{{item.name}}</div> -->
          <!-- <div class="item" v-for="(item, index) in optionList.slice(3, 4)" :key="'b' + index" :class="{active: item.active}" @click="handlerListOption(3)">{{item.name}}</div> -->
          <div class="item" v-for="(item, index) in optionList.slice(4, 5)" :key="'c' + index" :class="{active: item.active}" @click="handlerListOption(4)">{{item.name}}</div>
        </div>
        <div class="searchBar">
          <input type="text" placeholder="请输入关键字" v-model="optionList[currentActiveOptionIndex].filter.keyword" @keyup.enter="enterSearch('enter')">
          <div class="button" @click="enterSearch('enter')"></div>
        </div>
        <!-- <div class="selectBar" v-if="optionList[4].active">
          <el-select v-model="optionList[1].filter.deptId" placeholder="请选择" @change="(v)=>{handlerRyFilter(-1, v)}">
            <el-option-group v-for="group in locationDepts" :key="group.label" :label="group.label" >
              <template v-if="group.options">
                <el-option v-for="item in group.options" :key="item.value" :label="item.text" :value="item.value"></el-option>
              </template>
               <template v-if="!group.options">
                <el-option :label="group.text" :value="group.value"></el-option>
              </template>
              </el-option-group>
          </el-select>
        </div> -->
        <div class="title">{{optionList[currentActiveOptionIndex].name}}</div>

        <div class="sjItems" v-show="optionList[0].active">
          <div class="filters" style="padding: 5px 10px;">
            <div class="item" v-for="(item, index) in SJ_STATUS_FILTER" :key="index" :class="{active: item.status == optionList[0].filter.status}" @click="handlerSjStatusChanged(item, index)" style="width:150px;">{{item.name}}</div>
          </div>
          <div class="item" v-for="(item, index) in sjList" :key="index" @click="sjItemClicked(item, index);" :class="{active: item.active}">
            <div class="topp">
              <img v-if="item.img" :src="item.img | productEnv">
              <div class="sjtitle">{{item.name}}</div>
            </div>
            <div class="botmp">
              <div class="ren">{{item.userName}}</div>
              <div class="chd" :class="chdOptions[item.level] || 'aq'">{{item.level}}</div>
              <div class="shj">{{item.date.slice(0, 16)}}</div>
            </div>
          </div>
        </div>
        <div class="ryItems" v-show="optionList[4].active" v-loading="optionList[4].loading">
          <div class="filters">
            <div class="item" v-for="(item, index) in RY_STATUS_FILTER" :key="index" :class="{active: item.active}" @click="handlerRyFilter(index)">{{item.name}}</div>
          </div>
          <div class="ry-item" :class="item.status + ' ' + (item.active && 'active')" v-for="(item, index) in ryList" :key="index" @mousedown="showRyRightMenu($event, item)">
            <div class="len">
              <div class="name">{{item.name}}</div>
              <div class="status">{{item.status == 'online' ? '在线' : '离线'}}</div>
            </div>
            <div class="len">
              <div class="time">{{item.time.slice(5, 16)}}</div>
              <div class="time-use">{{item.shichang}}</div>
              <div class="distance">{{item.dist}}</div>
            </div>
          </div>
        </div>

        <!-- 会办 -->
        <div class="sjItems" v-show="optionList[1].active">
          <div class="filters" style="padding: 5px 10px;" v-if="optionList[1].statusFilter">
            <div class="item" v-for="(item, index) in optionList[1].statusFilter" :key="index" :class="{active: item.status == optionList[1].filter.status}" @click="handlerSjStatusChanged(item, index)" style="width:150px;">{{item.name}}</div>
          </div>
          <div class="item" v-for="(item, index) in optionList[1].list" :key="index" @click="optionList[1].itemClick(item, index);" :class="{active: item.active}">
            <div class="topp">
              <img :src="item.img | productEnv" v-if="item.img ">
              <div class="sjtitle">{{item.name}}</div>
            </div>
            <div class="botmp">
              <div class="ren">{{item.userName}}</div>
              <div class="chd" :class="chdOptions[item.level] || 'aq'">{{item.level}}</div>
              <div class="shj">{{item.date.slice(0, 16)}}</div>
            </div>
          </div>
        </div>

        <!-- 监控 -->
        <div class="cameraItems" v-show="optionList[3].active">
          <div class="item" :class="item.active && 'active'"  v-for="(item,id) in optionList[3].list" :key="id" @click="cameraItemClicked(item);">
            <div class="name">{{item.name}}</div>
            <div class="addr">地址：{{item.addr}}</div>
          </div>
        </div>

        <div class="searchFrame" v-show="showSearchFrame">
          <div class="clsbtn" @click="showSearchFrame = false;">×</div>
          <div class="form">
            <div class="len">
              <div class="t">关键字：</div>
              <div class="input"><input type="text" v-model="optionList[0].filter.keyword"></div>
            </div>
            <div class="len">
              <div class="t">日期：</div>
              <div class="input">
                <el-date-picker class="lw-datepicker" v-model="optionList[0].filter.time" type="date" placeholder="选择日期" />
              </div>
            </div>
            <div class="len">
              <div class="t">所属网格：</div>
              <el-cascader class="lw-selector"
                clearable
                change-on-select
                :options="gridNoArr"
                :props="{value: 'id', label: 'name', children: 'child'}"
                v-model="optionList[0].filter.grid">
              </el-cascader>
            </div>
            <div class="len btns">
              <div class="btn search" @click="enterSearch"></div>
              <div class="btn cz" @click="resetSearch"></div>
            </div>
          </div>
        </div>
        <div class="pagebtns">
          <button type="button" class="btn1" @click="pageNumberChanged(-1)" :disabled="optionList[currentActiveOptionIndex].isFirstPage || optionList[currentActiveOptionIndex].currentPage == 1">上一页</button>
          <button type="button" class="btn1" @click="pageNumberChanged(1)" :disabled="optionList[currentActiveOptionIndex].isLastPage || optionList[currentActiveOptionIndex].currentPage >= optionList[currentActiveOptionIndex].totalPage">下一页</button>
        </div>
      </div>
      <div class="rightFrame" v-show="showRightDetail">
        <div class="back-bar" @click="showRightDetail=false">返回“{{optionList[currentActiveOptionIndex].name}}”列表</div>
        <div class="item-detail-info" v-if="optionList[0].active">
          <div class="currentSj">
            <div class="title">{{sjInfo.base.title}}</div>
            <div class="imgView" v-viewer>
              <div v-for="(item, index) in sjInfo.base.imgs" :key="index" class="imgDiv"
                :class="{afterDo: item.status == 1}">
                <img :src="item.url | productEnv" alt="">
              </div>
            </div>
            <div class="abstracts" >
              <div class="item">
                <div class="key">事发地址：</div>
                <div class="value">{{sjInfo.base.addr}}</div>
              </div>
              <div class="item">
                <div class="key">上报人：</div>
                <div class="value">{{sjInfo.base.userName}} <img @click="openVideoCamera({userId: sjInfo.base.userId, name: sjInfo.base.userName})" src="/static/imgs/zhdd/23.png" style="margin-left: 10px;cursor:pointer;"> </div>

              </div>
              <div class="item">
                <div class="key">上报时间：</div>
                <div class="value">{{sjInfo.base.date}}</div>
              </div>
              <div class="item">
                <div class="key">联系方式：</div>
                <div class="value">{{sjInfo.base.phone}}</div>
              </div>
            </div>
            <div class="viewbtn" @click="showSjDetail(sjInfo.base)"></div>
          </div>
          <div class="extra">
            <div class="zbry title" v-show="sjInfo.person && sjInfo.person.length">周边人员</div>
            <div class="exscroll">
              <div class="item" v-for="(item, index) in sjInfo.person" :key="index">
                <div class="t" style="min-width: 80px;">{{item.name}}</div>
                <div class="t" style="min-width: 130px;">{{item.phone}}</div>
                <div class="t" style="min-width: 80px;">{{item.dist}}</div>
                <div class="btns">
                  <div class="voice" style="display:none;"></div>
                  <div class="video" @click="openVideoCamera(item)"></div>
                  <div class="track" @click="showPersonPath(item)"></div>
                </div>
              </div>
            </div>
            <div class="zbjk title" v-show="sjInfo.camera && sjInfo.camera.length">周边监控</div>
            <div class="exscroll">
              <div class="item" v-for="(item, index) in sjInfo.camera" :key="index">
                <div class="t" style="min-width: 180px;">{{item.name}}</div>
                <div class="t" style="min-width: 80px;">{{item.dist}}</div>
                <div class="btns">
                  <div class="camera" @click="showCamera(item)"></div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="item-detail-info" v-if="optionList[3].active && optionList[3].activeItem">
          <div class="currentSj">
            <div class="title">{{optionList[3].activeItem.base.title}}</div>
            <div class="abstracts" >
              <div class="item">
                <div class="key">地址：</div>
                <div class="value">{{optionList[3].activeItem.base.addr}}</div>
              </div>
              <div class="item" style="display:none;">
                <div class="key">负责人：</div>
                <div class="value">{{optionList[3].activeItem.base.fzr}}</div>
              </div>
              <div class="item">
                <div class="key">联系方式：</div>
                <div class="value">{{optionList[3].activeItem.base.phone}}</div>
              </div>
            </div>
          </div>
          <div style="display: flex;">
            <div class="actionb" @click="showCamera(optionList[3].activeItem)" style="color: white;font-size: 26px;cursor: pointer;width: 180px;border-radius: 10px;height: 46px;line-height: 46px;border: 2px solid #83ffce;text-align: center;margin: 0 auto 15px;">播放</div>
          </div>
          <div class="extra">
            <div class="zbry title">周边人员</div>
            <div class="exscroll">
              <div class="item" v-for="(item, index) in optionList[3].activeItem.person" :key="index">
                <div class="t" style="min-width: 80px;">{{item.name}}</div>
                <div class="t" style="min-width: 130px;">{{item.phone}}</div>
                <div class="t" style="min-width: 80px;">{{item.dist}}</div>
                <div class="btns">
                  <div class="voice" style="display:none;"></div>
                  <div class="video" @click="openVideoCamera(item)"></div>
                  <div class="track" @click="showPersonPath(item)"></div>
                </div>
              </div>
            </div>
            <div class="zbjk title">周边监控</div>
            <div class="exscroll">
              <div class="item" v-for="(item, index) in optionList[3].activeItem.camera" :key="index">
                <div class="t" style="min-width: 180px;">{{item.name}}</div>
                <div class="t" style="min-width: 80px;">{{item.dist}}</div>
                <div class="btns">
                  <div class="camera" @click="showCamera(item)"></div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="item-detail-info" v-if="optionList[4].active">
          <div class="flex">
            <div class="currentSj" style="margin: 30px 40px;">
              <div class="flex">
                <div class="headImg" v-viewer><img :src="(ryInfo.base.icon || '/websites/login/image/default.png') | productEnv" alt=""></div>
                <div>
                <div class="title">{{ryInfo.base.userName}}</div>
                  <div class="abstracts" >
                    <div class="item">
                      <div class="value">{{ryInfo.base.deptName}}</div>
                    </div>
                    <div class="item">
                      <div class="value">{{ryInfo.base.phone}}</div>
                    </div>
                  </div>
                </div>
              </div>
              <div style="display:flex;">
                <div class="actionb" @click="showPersonPath(activePerson)">轨迹播放</div>
                <div class="actionb" @click="openVideoCamera({userId: ryInfo.base.id, name: ryInfo.base.userName})">视频对讲</div>
              </div>
            </div>
          </div>
          <div class="extra">
            <div class="zbry title">周边事件</div>
            <div class="exscroll">
              <div class="item" v-for="(item, index) in ryInfo.event" :key="index">
                <div class="t sjname" @click="showSjDetail(item)">{{item.name}}</div>
                <div class="t" style="min-width: 80px;">{{item.dist}}</div>
              </div>
            </div>
            <div class="zbjk title" v-if="ryInfo.camera && ryInfo.camera.length">周边监控</div>
            <div class="exscroll">
              <div class="item" v-for="(item, index) in ryInfo.camera" :key="index">
                <div class="t" style="min-width: 180px;">{{item.name}}</div>
                <div class="t" style="min-width: 80px;">{{item.dist}}</div>
                <div class="btns">
                  <div class="camera" @click="showCamera(item)"></div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="sj35" v-if="useWurenji" :class="{sj35_on: wrjFlying}" @click="wrjFlying = !wrjFlying;showWrjPath();"></div>
    <right-menu :pop-items="popItems" :mouse="mousePosition" @ListItemClick="listItemClick"/>
    <right-menu :pop-items="popItems4Camera" :mouse="mousePosition4Camera" @ListItemClick="showCameraFrame"/>

    <transition-group :duration="500" enter-active-class="animated fadeInUp" leave-active-class="animated fadeOut">
      <div id="wghfx_0" class="wghfx" v-if="showSphs" style="overflow:hidden;" key="1">
        <iframe :src="'/datav/view/video/video.jsp' | productEnv" frameborder="0" style="
            width: 100%;
            height: 100%;
        "></iframe>
      </div>
      <div id="wghfx_1" class="wghfx" v-if="cameraUrl" style="overflow:hidden;" key="2">
        <iframe :src="cameraUrl" frameborder="0" style="
            width: 100%;
            height: 120%;
        "></iframe>
      </div>
    </transition-group>
  </div>
</template>

<script>

  // import LwMapThing from './lwmap/thing/index';
  import LwMap84 from './lwmap/84/index';
  import LwMap from './lwmap/gaode/index';
  // import LwMap from './lwmap/84/index';
  import G2 from '@antv/g2';
  import draggable from 'vuedraggable';
  import TimeSlider from './component/TimeSlider/Index';
  import BeautyBall from './component/BeautyBall/index';
  import AnimatedNumber from "animated-number-vue";
  import _ from 'lodash';
  const fillColors = ['#A3FF73', '#CC00FF', '#FF7575', '#FFFF73', '#FFFF73', '#DF73FF', '#DF73FF', '#FFFF73', '#FF7575', '#DF73FF'];
  const APIDATA = window.$APIDATA;
  const layui = require('layui');
  var boundaryData = '';
  var SJ_STATUS_FILTER = [
    // {name: '全部', active: true, status: ''},
    {name: '待处理', active: true, status: '待处理'},
    {name: '处理中', active: false, status: '处理中'},
    {name: '已处理', active: false, status: '已处理'}
  ];

  var RY_STATUS_FILTER = [
    {name: '全部', active: true, status: 'all'},
    {name: '执法员', active: false, status: 'zfy'},
    {name: '网格员', active: false, status: 'wgy'}
  ];
  const chdOptions = {
    '一般': 'yb',
    '紧急': 'jj'
  };
  export default {
    name: 'Map',
    components: {draggable, TimeSlider, BeautyBall, AnimatedNumber},
    data () {
      var userId = this.$route.query.userId || this.$db.get('userId') || (process.env.NODE_ENV == 'development' ? '98acjf9ecn0h' : '');
      // userId = '5cydj8x66fvf'; // 镇级账号测试
      var spaceId = this.$route.query.spaceId || this.$db.get('spaceId') || '';
      return {
        userCode: 1,
        userId,
        spaceId,
        currentAreaName: '',
        showTownSelector: false,
        showRightDetail: false,
        showRlt: false,
        ssdtChartTab: '网格员',
        showSphs: false,
        cameraUrl: '',
        SJ_STATUS_FILTER,
        RY_STATUS_FILTER,
        chdOptions,
        towns: [],
        tongjiInfo: {
          wgy: {
            todayCount: "0",
            totalCount: "0",
            dclCount: 0,
            clzCount: 0,
            ybjCount: 0,
            lv: 100
          },
          zfy: {
            totalCount: 0,
            todayCount: 0,
            yclCount: 0,
            clzCount: 0,
            lv: 50
          }
        },
        tjInfo: {
          licheng: 0,
          hours: 0,
          event: {
            today: 0,
            total: 0,
            dcl: 0,
            ycl: 0,
            bjl: 0
          }
        },
        qzbl: {qz: false, bl: false},
        useWurenji: this.$Config.useWurenji || '',
        kqInfo: { wgy: {qq: 2, yc: 0, zc: 85}, zfdy: {qq: 1, yc: 0, zc: 40} },
        currentActiveOptionIndex: 0,
        optionList: [
          // eslint-disable-next-line
          {name: '事件', active: true, currentPage: 1, isFirstPage: true, isLastPage: false,
          filter: {
            keyword: '',
            grid: [],
            time: '',
            status: '待处理'
          }},
          // eslint-disable-next-line
          {name: '会办', active: false, currentPage: 0, isFirstPage: true, isLastPage: false, list: [], cloneSj: true,
            itemType: 'Event',
            statusFilter: [{name: '全部', active: true, status: ''},
            {name: '待处理', active: false, status: '待处理'},
            {name: '已处理', active: false, status: '已处理'}],
            showMarker: true,
            activeItem: '',
            itemClick: (item) => {
              this.openInfoContent(item.entity, item.id);
            },
            listApi: 'api/v3/zhdd/hb/hbQueryEvents.jsp',
            detailApi: '',
            filter: {
              keyword: '',
              grid: [],
              time: '',
              status: ''
          }},
          // eslint-disable-next-line
          {name: '预警', active: false, currentPage: 0, isFirstPage: true, isLastPage: false, list: [], cloneSj: true,
            activeItem: '',
            listApi: 'api/v1/12345/query12345List.jsp',
            detailApi: 'api/v1/12345/get12345Info.jsp',
            filter: {
              keyword: '',
              grid: [],
              time: '',
              status: '待处理'
          }},
          // eslint-disable-next-line
          {name: '监控', active: false, currentPage: 0, isFirstPage: true, isLastPage: false, list: [], camera: true,
            itemType: 'Camera',
            activeItem: '',
            listApi: 'api/yth/zhdd/getCameras.jsp',
            detailApi: 'api/v1/zhcg/getZhcgEventInfo.jsp',
            filter: {
              keyword: '',
              grid: [],
              time: '',
              status: ''
          }},
          {
            name: '人员',
            active: false,
            loading: true,
            pageSize: 7,
            currentPage: 1,
            isFirstPage: true,
            isLastPage: false,
            // 过滤条件
            filter: {
              status: '',
              deptId: '',
              keyword: ''
            }
          }
        ],
        keyword: '',
        showSearchFrame: false,
        // 地图部分
        showGrids: true,
        showAllPerson: true,
        ryList: [],
        sjList: [],
        dbList: [],
        sjInfo: {
          base: {
            title: "",
            addr: "",
            date: "",
            userName: "",
            phone: "",
            imgs: [
            ]
          },
          person: [
          ],
          camera: [
          ]
        },
        ryInfo: {
          base: {id: '', deptName: '', userName: '', phone: ''},
          event: [],
          camera: []
        },
        activePerson: '',
        popItems: [
          { class: 'fa fa-wrench', txt: '轨迹回放' },
          { class: 'fa fa-check', txt: '视频通话' }
        ],
        popItems4Camera: [
          { class: 'fa fa-wrench', txt: '播放' }
        ],
        mousePosition: ['close'],
        mousePosition4Camera: ['close'],
        pathSpeed: 1000,
        gridNoArr: [],
        locationDepts: [],
        wrjFlying: ''
      };
    },
    methods: {
      backIconClick: function () {
        if (this.cameraUrl) {
          this.cameraUrl = '';
        } else if (this.showSphs) {
          this.showSphs = false;
        } else {
          history.go(-1);
        }
      },
      clearFeatures: function (f1 = 1, f2 = 1, f3 = 1) {
        if (f1) {
          this.map.removeFeature('FeatureCollection');
        }
        if (f2) {
          this.map.removeFeature('Feature');
        }
        if (f3) {
          this.map.removeFeature('Terminal');
        }
      },
      handlerAreaChange: function (item, index) {
        var vm = this;
        vm.spaceId = item.spaceId;
        vm.$db.set('spaceId', item.spaceId);
        vm.showTownSelector = false;
        vm.$Util.toggleAttr(vm.towns, index);
        vm.getTongjiData();
        vm.enterSearch();
        if (index) {
          // vm.clearFeatures();
          vm.currentAreaName = item.spaceName;
          this.map.removeFeature('3DBoundarys');
          vm.addFeatures();
          // vm.currentGirdNo = item.id;
        } else {
          vm.currentAreaName = vm.topSpaceName;
          vm.map.setCenterAndZoom(vm.$Config.ZHDD_MAP_CENTER, vm.$Config.ZHDD_MAP_ZOOM);
          vm.currentWgCenterZoom = '';
          this.map.removeFeature('3DBoundarys');
          vm.addFeatures();
        }
      },
      handlerElCheckBox: function (val, name) {
        if (name == 'showGrids') {
          if (val) {
            this.addFeatures();
          } else {
            this.map.removeFeature('3DBoundarys');
          }
        }
        if (name == 'showAllPerson') {
          if (val) {
            this.showMarkers(4);
          } else {
            this.map.clearActivities((n) => {
              return n.lwType == 'PersonMarker';
            });
          }
        }
      },
      handlerListOption: function (index) {
        var vm = this;
        if (vm.showSearchFrame) return;
        vm.$Util.toggleAttr(this.optionList, index);
        vm.currentActiveOptionIndex = index;
        // 地图初始化
        if (vm.currentWgCenterZoom) {
          vm.map.setCenterAndZoom(vm.currentWgCenterZoom[0], vm.currentWgCenterZoom[1]);
        } else {
          vm.map.setCenterAndZoom(vm.mapCenter, vm.$Config.ZHDD_MAP_ZOOM);
        }
        vm.map.showInfoWindow('', vm.mapCenter);
        vm.showMarkers(index);
        if (this.optionList[index].currentPage == 0) {
          // 非事件和人员 懒加载列表
          // this.loadCameras(this.optionList[index]);
          this.loadEvents(this.optionList[index]);
        }
        if (!vm.showGrids) {
          vm.showGrids = true;
          vm.handlerElCheckBox(1, 'showGrids');
        }
        // vm.showRightCameraList();
      },
      loadEvents: function (option, page = 1) {
        var vm = this;
        option.currentPage = page;
        vm.getAndLoad(option.name + '列表', option.listApi + '?status=' + option.filter.status, function (data) {
          data.data instanceof Array && (data.list = data.data);
          data.list.forEach((n, i) => {
            n.active = false;
          });
          // if (data.list.length) {
          //   vm.sjItemClicked(data.list[0], 0, true);
          // }
          option.isLastPage = data.isLastPage;
          option.list = data.list;
          (option.camera || option.showMarker) && vm.showMarkers(vm.currentActiveOptionIndex);
        });
      },
      loadCameras: function (item, page = 1) {
        var vm = this;
        item.currentPage = page;
        vm.getAndLoad(item.name, 'api/v1/zhdd/getCameras.jsp?' + vm.$Util.stringify({
          pageNo: page,
          keyword: item.keyword,
          type: item.type
        }), function (data) {
          item.list = data.data;
          item.totalPage = Math.ceil(item.list.length / item.pageSize);
          if (data.data.length && !item.activeItem) {
            vm.showCameraDetail(item, 0);
          }
          item.list.forEach(function (obj) {
            vm.showCameraMarker(obj);
          });
        });
      },
      showCameraMarker: function (item) {
        var vm = this;
        const params = [
          ['/static/imgs/zhdd/tubiao2.gif', [120, 120], [60, 60]],
          ['/static/imgs/zhdd/dd-7.png', [35, 43], [18, 43]]
        ];
        var parr = item.warning ? params[0] : params[1];
        // var offsetPonit = [parseFloat(item.lng) + this.mapOffset[0], parseFloat(item.lat) + this.mapOffset[1]];
        // this.map.setCenterAndZoom(offsetPonit, 15);
        this.map.addMarker('CameraMarker' + item.id, parr[0], [item.lng, item.lat], parr[1], parr[2], (e) => {
          var clicked = vm.cameraItemClicked(item);
          if (clicked) {
            vm.mousePosition4Camera = [1920 / 2, 1080 / 2];
            vm.cameraIdforPop = item.id;
          }
        }, {
          lwType: 'CameraMarker'
        });
        // var marker = this.map.mapBox['CameraMarker'];
        // marker && this.map.setAnimation(marker, 'BOUNCE', 5000);
      },
      showCameraFrame: function (id) {
        !id && (id = this.cameraIdforPop);
        id && window.layer.open({
          closeBtn: true,
          type: 2,
          title: false,
            shadeClose: false,
            shade: 0,
            skin: 'layerSkin',
            area: ['90%', '920px'],
            content: [process.env.API_URL + "/datav/view/hikvision/iSecure/video.jsp?id=" + id, 'no']
          }
        );
      },
      cameraItemClicked: function (item) {
        // var option = this.optionList.find((opt) => opt.active);
        // var listIndex = option.list.findIndex((obj) => obj.id == item.id);
        // if (!option.activeItem || item.id != option.activeItem.base.id) {
        //   var marker = this.map.mapBox['CameraMarker' + item.id];
        //   marker && this.map.setAnimation(marker, 'BOUNCE', 5000);
        //   this.showCameraDetail(option, listIndex);
        // } else {
        //   return item; // 已经为active状态
        // }
        if (item.url) {
          this.cameraUrl = 'http://xxk.datav.jyit.org:9125/datav/videocamera/index.html?code=' + item.url;
        }
      },
      showCameraDetail: function (item, index) {
        var vm = this;
        vm.$Util.toggleAttr(item.list, index);
        var id = item.list[index].id;
        vm.getAndLoad(item.name + '详情', 'api/v1/zhdd/getCameraInfo.jsp?id=' + id, function (data) {
          item.activeItem = data;
        });
      },
      showMarkers: function (index) {
        var vm = this;
        if (index == 0) {
          vm.map.clearActivities();
          vm.map.removeMarkerAndPath();
          // 显示所有的代办事件
          vm.sjList.forEach((event) => {
            var src = event.level == '紧急' ? '/static/imgs/zhdd/jj.gif' : '/static/imgs/zhdd/30.png';
            vm.map.addMarker('ProEvent' + event.id, src, [event.lng, event.lat], [44, 70], [22, 66], function () {
              var offsetPonit = [parseFloat(event.lng) + vm.mapOffset[0], parseFloat(event.lat) + vm.mapOffset[1]];
              vm.map.setCenterAndZoom(offsetPonit, 15);
              vm.sjItemClicked(event, -1);
            }, {
              lwType: 'EventMarker'
            });
          });
        }
        if (index == 4) {
          vm.map.clearActivities();
          // 把所有人员标注在地图上
          vm.ryList.forEach((person) => {
            vm.map.addMarker('Person' + person.id, `/static/imgs/zhdd/28${person.type == 'law' ? 'law' : ''}.png`, [person.lng, person.lat], [30, 35], [15, 35], function (e) {
              var offsetPonit = [parseFloat(person.lng) + vm.mapOffset[0], parseFloat(person.lat) + vm.mapOffset[1]];
              vm.map.setCenterAndZoom(offsetPonit, 15);
              vm.map.setAnimation(this, 'BOUNCE', 2500);
              vm.ryList.forEach((n) => { n.active = false; });
              var activePerson = vm.ryList.find((n) => n.id == person.id);
              vm.showRenyanDetail(person.id);
              activePerson.active = true;
              vm.activePerson = activePerson;
            }, {
              lwType: 'PersonMarker'
            }, person.name);
          });
          this.showAllPerson = true;
        }
        if (index > 0 && index < 4) {
          vm.map.clearActivities();
          vm.map.removeMarkerAndPath();
          if (vm.optionList[index].itemType == 'Camera') {
            vm.optionList[index].currentPage && vm.optionList[index].list.forEach((camera) => {
              vm.showCameraMarker(camera);
            });
          } else if (vm.optionList[index].itemType == 'Event') {
            vm.optionList[index].list.forEach((event) => {
              vm.map.addMarker('ProEvent' + event.id, '/static/imgs/zhdd/30.png', [event.lng, event.lat], [44, 70], [22, 66], function () {
                vm.optionList[index].itemClick && vm.optionList[index].itemClick(event);
              }, {
                lwType: 'EventMarker'
              });
            });
          }
        }
      },
      handlerSjStatusChanged: function (item, index) {
        var vm = this;
        if (vm.currentActiveOptionIndex == 0) {
          if (item.status != vm.optionList[0].filter.status) {
            vm.$Util.toggleAttr(vm.SJ_STATUS_FILTER, index);
            vm.optionList[0].filter.status = item.status;
            vm.enterSearch('enter');
          }
        } else {
          var option = vm.optionList[vm.currentActiveOptionIndex];
          if (item.status != option.filter.status) {
            // vm.$Util.toggleAttr(option, index);
            option.filter.status = item.status;
            vm.enterSearch('enter');
          }
        }
      },
      handlerRyFilter: function (typeIndex, keyword, pageNo) {
        var vm = this;
        var option = this.optionList[this.currentActiveOptionIndex];
        if (typeIndex != -1) {
          vm.$Util.toggleAttr(this.RY_STATUS_FILTER, typeIndex);
          option.filter.status = this.RY_STATUS_FILTER[typeIndex].status;
          option.currentPage = 1;
        }
        // if (keyword) {
        //   option.filter.keyword = keyword;
        // }
        // 重新获取人员
        vm.optionList[4].loading = true;
        if (!pageNo) {
          vm.map.clearActivities((n) => n.lwType == 'PersonMarker');
        }
        vm.getAndLoad('人员列表', 'api/yth/zhdd/queryPersonLoc.jsp?' + vm.$Util.stringify({
          type: option.filter.status,
          keyword: option.filter.keyword,
          pageNo: pageNo || 1,
          pageSize: 7,
          spaceId: vm.spaceId
        }), function (data) {
          data.list.forEach((n) => { n.active = false; });
          vm.ryList = data.list;
          // vm.ryList.length && vm.showRenyanDetail(vm.ryList[0].id);
          if (vm.currentActiveOptionIndex == 4) {
            vm.showMarkers(4);
          }
          vm.optionList[4].loading = false;
          vm.optionList[4].isFirstPage = data.isFirstPage;
          vm.optionList[4].isLastPage = data.isLastPage;
        });
      },
      showSjDetail: function (item) {
        var url = '';
        var vm = this;
        if (vm.optionList[vm.currentActiveOptionIndex].filter.status == '待处理') {
          var sjItem = vm.sjList.find(n => n.active);
          url = `/general_10/zhzf/view/event/handlerView.jsp?fromDate=${sjItem.fromDate}&roleTypeId=${sjItem.roleTypeId}&id=${sjItem.id}`;
        } else {
          url = '/general_10/zhzf/view/event/eventView.jsp?id=' + item.id;
        }

        window.layer.open({
          closeBtn: true,
          type: 2,
          title: false,
            shadeClose: false,
            shade: 0,
            skin: 'layerSkin',
            area: ['90%', '920px'],
            content: [process.env.API_URL + url, 'no']
          }
        );
      },
      enterSearch: function (keyDown, refresh = false) {
        // 根据关键字搜索
        var option = this.optionList[this.currentActiveOptionIndex];
        if (option.name == '人员') {
          // option.filter.keyword = this.keyword;
          this.handlerRyFilter(-1, option.filter.keyword);
        }
        if (option.name == '事件') {
          let vm = this;
          let filter = option.filter;
          let condition = '';
          let keyword = option.filter.keyword;
          // if (keyDown == 'enter') {
          //   // 直接keyword搜索
          //   keyword = vm.keyword;
          //   option.filter.keyword = keyword;
          // } else {
          //   // 搜索按钮
          //   keyword = filter.keyword;
          //   vm.keyword = filter.keyword;
          // }
          let date = vm.$Util.getFmtDate(filter.time);
          let status = filter.status;
          let gridId = filter.grid[filter.grid.length - 1] || '';
          condition = vm.$Util.stringify({
            pageNo: refresh ? option.currentPage : 1,
            pageSize: 6,
            keyword,
            gridId,
            date,
            status,
            spaceId: vm.spaceId
          });
          vm.getAndLoad('事件搜索', 'api/other/zhdd/getSjList.jsp?' + condition, function (data) {
            data.list.forEach((n, i) => {
              n.active = false;
            });
            // if (data.list.length) {
            //   vm.sjItemClicked(data.list[0], 0, true);
            // }
            vm.sjList = data.list;
            vm.showMarkers(0);
            option.isFirstPage = data.isFirstPage;
            option.isLastPage = data.isLastPage;
            option.currentPage = 1;
          });
          vm.showSearchFrame = false;
        }
        if (option.cloneSj) { // 12345 或者 智慧城管
          let vm = this;
          let filter = option.filter;
          let condition = '';
          let keyword = '';
          if (keyDown == 'enter') {
            // 直接keyword搜索
            keyword = vm.keyword;
            option.filter.keyword = keyword;
          } else {
            // 搜索按钮
            keyword = filter.keyword;
            vm.keyword = filter.keyword;
          }
          let date = vm.$Util.getFmtDate(filter.time);
          let status = filter.status;
          let gridId = filter.grid[filter.grid.length - 1] || '';
          condition = vm.$Util.stringify({
            pageNo: 1,
            keyword,
            gridId,
            date,
            status
          });
          vm.getAndLoad(option.name + '搜索', `${option.listApi}?` + condition, function (data) {
            data.list.forEach((n, i) => {
              n.active = false;
            });
            // if (data.list.length) {
            //   vm.sjItemClicked(data.list[0], 0, true);
            // }
            option.list = data.list;
            option.isFirstPage = data.isFirstPage;
            option.isLastPage = data.isLastPage;
            option.currentPage = 1;
            vm.showMarkers(vm.currentActiveOptionIndex);
          });
          vm.showSearchFrame = false;
        }
        if (option.type) { // 监控类有type字段
          option.keyword = this.keyword;
          this.loadCameras(option, 1);
        }
      },
      resetSearch: function () {
        this.optionList[0].filter = {
          keyword: '',
          grid: [],
          time: ''
        };
      },
      showCamera: function (item) {
        // var url = item.url;
        // this.hlsSource[this.tpCamera].url = url;
        item.id && window.layer.open({
          closeBtn: true,
          type: 2,
          title: false,
            shadeClose: false,
            shade: 0,
            skin: 'layerSkin',
            area: ['90%', '920px'],
            content: [process.env.API_URL + "/datav/view/hikvision/iSecure/video.jsp?id=" + item.id, 'no']
          }
        );
      },
      showRyRightMenu: function (e, item) {
        var offsetPonit = [parseFloat(item.lng), parseFloat(item.lat)];
        this.map.setCenterAndZoom(offsetPonit, 15);
        var marker = this.map.mapBox['Person' + item.id];
        marker && this.map.setAnimation(marker, 'BOUNCE', 5000);
        if (!this.showAllPerson) {
          this.showMarkers(4);
        }
        if (this.activePerson != item) {
          this.showRenyanDetail(item.id);
          this.activePerson = item;
          this.ryList.forEach((n) => { n.active = false; });
          item.active = true;
        }
        // this.mousePosition = [e.clientX, e.clientY];
      },
      listItemClick: function (it) {
        if (it == 0) {
          // 轨迹播放
          this.showPersonPath(this.activePerson);
        } else {
          // 视频对讲
          this.openVideoCamera({
            userId: this.activePerson.id,
            name: this.activePerson.name
          });
        }
      },
      showWrjPath: function () {
        var vm = this;
        if (vm.wrjFlying) {
          vm.whileLoad('api/yth/wgh/fly.jsp?' + vm.$Util.stringify({
            spaceId: vm.spaceId,
            time: vm.wrjFinalTime || (process.env.NODE_ENV == "production" ? '' : 0)
          }), function (data) {
            // 判断轨迹有效
            var valid = data.length && data.length > 9;
            var pathData = [];
            if (valid) {
              data.forEach((n) => {
                var lnglat = n.lnglat.split(',');
                pathData.push([parseFloat(lnglat[0]), parseFloat(lnglat[1])]);
              });
              // 判断第一个点 和 最后一个点距离
              var firstPoint = pathData[0];
              var lastPoint = pathData[pathData.length - 1];
              var distance = Math.abs(firstPoint[0] - lastPoint[0]) + Math.abs(firstPoint[1] - lastPoint[1]);
              valid = distance > 0.0001;
            }
            if (valid) {
              // 最后一个点的时间为finalTime
              vm.wrjFinalTime = data[data.length - 1].time;
              if (!vm.wrjPoint) {
                // vm.pathData = pathData.slice(200);
                var wrjPoint = vm.map.addMarkerAndPathV2(pathData, './static/imgs/map/wrjmarker.png', [48, 48], [24, 24], '', [-25, 0], 'BM', 'blue', 4);
                vm.wrjPoint = wrjPoint;
                wrjPoint.afterMove(vm.showWrjPath);
                // wrjPoint.afterMove(() => {
                //   vm.wrjPoint.addPath(vm.pathData);
                // });
                wrjPoint.start(58);
              } else {
                // 当前路径追加
                vm.wrjPoint.addPath(pathData);
                // vm.wrjPoint.pathArr
              }
            } else {
              vm.wrjFlyTimeout = setTimeout(() => {
                vm.wrjFlying && vm.showWrjPath();
              }, 300);
              // vm.$message.warning('无人机位置未更新');
            }
          }, () => {
            vm.wrjFlying && vm.showWrjPath();
          });
        } else {
          // 停止飞行
          vm.wrjFinalTime = 0;
          vm.wrjPoint = null;
          vm.wrjFlyTimeout && clearTimeout(vm.wrjFlyTimeout);
        }
      },
      showPersonPath: function (item) {
        // 显示路径
        var vm = this;
        vm.map.clearActivities((n) => n.lwType == 'PersonMarker');
        vm.showAllPerson = false;
        vm.wrjFlying = false;
        vm.map.removeFeature('3DBoundarys');
        vm.showGrids = false;

        var dateObj = vm.$refs.timeSlider.getResult();
        // map.clear
        vm.getAndLoad('获取人员路径', 'api/v1/zhdd/getRoute.jsp?' + vm.$Util.stringify({
          qz: vm.qzbl.qz,
          bl: vm.qzbl.bl,
          userId: item.id,
          dateFrom: dateObj.start + ':00.000',
          dateTo: dateObj.end + ':00.000'
        }), vm.showPeoplePath, item);
        this.activePerson = item;
      },
      sliderChanged: function () {
        if (this.currentActiveOptionIndex == 4 && this.activePerson) {
          this.showPersonPath(this.activePerson);
        }
      },
      speedChanged: function () {
        var vm = this;
        if (vm.peoPoint) {
          vm.peoPoint.setSpeed(this.pathSpeed);
        }
      },
      pageNumberChanged: function (offset) {
        var vm = this;
        var option = this.optionList[this.currentActiveOptionIndex];
        option.currentPage += offset;
        if (option.name == '事件') {
          let filter = option.filter;
          let date = vm.$Util.getFmtDate(filter.time);
          let gridId = filter.grid[filter.grid.length - 1] || '';
          let status = filter.status;
          vm.getAndLoad('事件列表', 'api/other/zhdd/getSjList.jsp?' + vm.$Util.stringify({
            pageNo: option.currentPage,
            pageSize: 6,
            keywords: filter.keyword,
            spaceId: vm.spaceId,
            gridId,
            date,
            status
          }), function (data) {
            vm.sjList = data.list;
            vm.showMarkers(0);
            option.isFirstPage = data.isFirstPage;
            option.isLastPage = data.isLastPage;
          });
        }
        if (option.name == '人员') {
          this.handlerRyFilter(-1, null, option.currentPage);
        }
        if (option.name == '监控' || option.name == '智慧城管' || option.name == '催办事件') {
          let filter = option.filter;
          let date = vm.$Util.getFmtDate(filter.time);
          let gridId = filter.grid[filter.grid.length - 1] || '';
          let status = filter.status;
          vm.getAndLoad(option.name + '列表', option.listApi + '?' + vm.$Util.stringify({
            pageNo: option.currentPage,
            keyword: filter.keyword,
            gridId,
            date,
            status
          }), function (data) {
            data.data && (data.list = data.data);
            option.list = data.list;
            option.camera && vm.showMarkers(vm.currentActiveOptionIndex);
            option.isFirstPage = data.isFirstPage;
            option.isLastPage = data.isLastPage;
          });
        }
      },
      // 统一请求加载方法
      getAndLoad: function (chartName, apiUrl, callback, ...params) {
        var vm = this;
        var keys = Object.keys(APIDATA);
        var key = '';
        keys.forEach(k => {
          if (apiUrl.includes(k)) {
            key = k;
          }
        });
        if (APIDATA[key]) {
          callback(APIDATA[key].data, params);
          return;
        }
        vm.$http((process.env.NODE_ENV == "production" ? '/' : '') + apiUrl).then(function (res) {
          if (res.data && res.data.code == 0) {
            callback(res.data.data, params);
          } else {
            // vm.$notify.error({ title: '错误', message: `获取数据失败[${chartName}]` });
            console.error({ title: '错误', message: `服务器未响应[${chartName}]` });
          }
        }, function () {
          console.error({ title: '错误', message: `服务器未响应[${chartName}]` });
        });
      },
      whileLoad: function (apiUrl, callback, errorCallback) {
        var vm = this;
        vm.$http((process.env.NODE_ENV == "production" ? '/' : '') + apiUrl).then(function (res) {
          if (res.data && res.data.code == 0) {
            callback(res.data.data);
          } else {
            errorCallback();
          }
        }, function () {
          errorCallback();
        });
      },
      showSearch: function () {
        if (this.currentActiveOptionIndex == 0) {
          this.showSearchFrame = true;
        } else {
          this.enterSearch('enter');
        }
      },
      mapBoxManager: function (status, layer) {
        if (status) {
          // 展示
          this.map.add(this.mapBox[layer]);
        } else {
          // 移除
          this.map.remove(this.mapBox[layer]);
        }
      },
      sjItemClicked: function (item, index, first = false) {
        var vm = this;
        if (!first) {
          var offsetPonit = [parseFloat(item.lng) + vm.mapOffset[0], parseFloat(item.lat) + vm.mapOffset[1]];
          vm.map.setCenterAndZoom(offsetPonit, 15);
          // 地图上标注
          var src = item.level == '紧急' ? '/static/imgs/zhdd/jj.gif' : '/static/imgs/zhdd/30.png';
          vm.map.addMarker('CurrentEvent', src, [item.lng, item.lat], [60, 90], [30, 75], function () {
            vm.map.setCenterAndZoom(offsetPonit, 15);
            vm.sjItemClicked(item, index);
          }, {
            lwType: 'EventMarker'
          });
          // vm.map.showInfoWindow(item.name, [item.lng, item.lat], 'middle-left');
        }
        var option = vm.optionList[vm.currentActiveOptionIndex];
        if (option.detailApi) {
          vm.getAndLoad('获取详情', (option.detailApi ? option.detailApi : 'api/v3/zhdd/getEventInfo.jsp') + '?id=' + item.id, function (data) {
            option.activeItem = data;
            vm.showRightDetail = true;
            vm.$Util.toggleAttr(option.list, index);
          });
        } else {
          vm.$Util.toggleAttr(vm.sjList, index);
          window.layer.open({
            closeBtn: true,
            type: 2,
            title: false,
            shadeClose: false,
            shade: 0,
            skin: 'layerSkin bhheight',
            area: ['70%', '760px'],
            content: [`http://2.16.66.41:8888/zhwx-1.0.0/lw/issuePending_detail/${item.id}?uid=${vm.userId}&spaceId=${vm.spaceId}`],
            end: () => {
              vm.enterSearch();
            }
          });
        }
      },
      addOuterPolygon: function (data) {
        var vm = this;
        if (!vm.map.addOuterPolygon) {
          return;
        }
        if (data instanceof Array) {
          vm.map.addOuterPolygon(data);
        } else {
          vm.map.addOuterPolygon([data]);
        }
      },
      initMap: function () {
        var vm = this;
        var isNy = location.href.includes('bh.html');
        var mapType = vm.$route.query.map || (isNy ? 'tian' : 'gaode');
        var Construter = {gaode: LwMap, tian: LwMap84}[mapType];
        var map = new Construter('map-container', vm.mapCenter, [vm.$Config.ZHDD_MAP_ZOOM, 3, 20], {
          pitch: vm.$Config.ZHDD_MAP_PITCH,
          viewMode: '3D',
          rotation: vm.$Config.ZHDD_MAP_ROTATION
        });
        vm.map = map;
        return map.loadPromise;
      },
      addFeatures: function () {
        var vm = this;
        var spaceName = vm.towns.find(n => n.spaceId == vm.spaceId).spaceName;
        if (vm.spaceId != vm.topSpaceId) {
          var featureData = boundaryData.features.find((n) => n.properties.name == spaceName);
          var zoom2 = vm.$Config.ZOOM_2;
          if (['胡埭镇', '荣巷街道'].includes(spaceName)) {
            zoom2 += 1;
          }
          if (['蠡湖街道', '河埒街道'].includes(spaceName)) {
            zoom2 += 2;
          }
          vm.map.setCenterAndZoom(featureData.properties.cp, zoom2);
          vm.currentWgCenterZoom = [featureData.properties.cp, zoom2];
          if (featureData.features.length) {
            // 显示二级网格 （村里面的网格 临时网格）
            vm.addOuterPolygon(featureData.features);
            featureData.features.forEach((fl2, index) => {
              vm.map.add3DBoundaryByFeatureV2(fl2, fillColors[index % 10], 0.75, 1000, [3, 20], '', '3DBoundarys');
            });
          } else {
            vm.addOuterPolygon(featureData);
            vm.map.add3DBoundaryByFeatureV2(featureData, '#1ac9ff', 0.3, 1600, [3, 20], '', '3DBoundarys');
          }
        } else {
          vm.addOuterPolygon(boundaryData.features);
          boundaryData.features.forEach((feature, index) => {
            // 显示一级网格 （所有村 显示范围 3-14.5）
            vm.map.add3DBoundaryByFeatureV2(feature, fillColors[index % 10], 0.75, 2500, [3, 20], '', '3DBoundarys');
          });
        }
      },
      showPeoplePath: function (data, params) {
        var vm = this;
        if (!data || !data.length) {
          vm.$message.warning('该人员在时间段内无轨迹信息');
          return;
        }
        var pathData = [];

        // 组装轨迹
        data.forEach((n, index) => {
          pathData.push([]);
          n.forEach(j => {
            pathData[index].push([j.lng, j.lat]);
          });
        });

        // 调整视角
        var firstPoint = pathData[0][0];
        var offsetPonit = [parseFloat(firstPoint[0]) + vm.mapOffset[0], parseFloat(firstPoint[1]) + vm.mapOffset[1]];
        vm.map.setCenterAndZoom(offsetPonit, 15);

        // 添加路径和marker 开始移动
        var peoPoint = vm.map.addMarkerAndPath(pathData, `/static/imgs/zhdd/28${params[0].type == 'law' ? 'law' : ''}.png`, [30, 35], [15, 35], params[0].name, [-25, 0], 'BM', 'red', 4);
        vm.peoPoint = peoPoint;
        peoPoint.init();
        peoPoint.run(this.pathSpeed);
      },
      handlerMarkerMove: function (signal) {
        var vm = this;
        if (!vm.peoPoint) {
          return;
        }
        if (signal == 1) {
          if (vm.peoPoint.status == 2) {
            vm.peoPoint.resume();
          } else if (vm.peoPoint.status == 1) {
            vm.peoPoint.pause();
          }
        }
        if (signal == 0) {
          if (vm.peoPoint.status == 0) {
            vm.peoPoint.run(this.pathSpeed, true);
          } else {
            vm.peoPoint.stop();
          }
        }
        if (signal == 2) {
          // 快进5步
          vm.peoPoint.changeStep(5);
        }
        if (signal == 3) {
          // 倒退5步
          vm.peoPoint.changeStep(-10);
        }
      },
      openVideoCamera: function (item) {
        var params = {
          senderId: this.userId,
          senderName: '指挥中心',
          receiverId: item.userId,
          receiverName: item.name
          // ,
          // microphone: true,
          // hasWebCam: true,
          // zoom: 1.2
        };
        // this.showDialog = true;
        var url = this.$Config.VIDEO_CAMERA_URL + '&' + this.$Util.stringify(params);
        // this.cameraSrc = url;
        var top = (window.screen.height - 850) / 2;
        var left = (window.screen.width - 900) / 2;
        window.open(url, '视频对讲',
          `height=850,width=900,top=${top},left=${left},toolbar=no,menubar=no,
          scrollbars=no,resizable=no,location=no,status=no,titlebar=no`
        );
      },
      showRightCameraList: function () {
        // 事件不处理
        if (this.currentActiveOptionIndex == 0) { return; }
        var option = this.optionList[this.currentActiveOptionIndex];
        var type = option.type || 'common';
        var cameraList = this.cameraDictionary[type];
        if (cameraList) {
          this.hlsSource.forEach((src, index) => {
            var camera = cameraList[index];
            if (camera) {
              src.id = camera.id + '';
              src.url = camera.url;
            }
          });
        }
      },
      showRenyanDetail: function (id) {
        var vm = this;
        vm.showRightDetail = true;
        vm.getAndLoad('人员详情', 'api/v1/zhdd/getPersonInfo.jsp?id=' + id, function (data) {
          vm.ryInfo = data;
        });
      },
      rightMenuClicked: function (index) {
        var vm = this;
        vm.$Util.toggleAttr(vm.rigthMenus, index);
      },
      handleMessage: function (event) {
        var vm = this;
        const data = event.data;
        switch (data.cmd) {
          case 'updateEvents':
            vm.getAndLoad('事件列表', 'api/other/zhdd/getSjList.jsp?status=待处理&pageSize=6&spaceId=' + vm.spaceId, function (data) {
              data.list.forEach((n, i) => {
                n.active = false;
              });
              vm.sjList = data.list;
              vm.showMarkers(0);
            });
            break;
          case 'closeIframe' :
            window.layer.closeAll();
          break;
          case 'refreshList' :
            vm.enterSearch();
          break;
        }
        console.log(event);
      },
      openInfoContent: function (entityName, id) {
        var vm = this;
        var params = {
          entityName,
          id
        };
        window.layer.open({
          closeBtn: true,
          type: 2,
          title: false,
            shadeClose: false,
            shade: 0,
            skin: 'layerSkin',
            area: ['90%', '760px'],
            content: [process.env.API_URL + "/datav/view/viewContent.jsp?" + vm.$Util.stringify(params), 'no']
          }
        );
      },
      closeNotify: function (id) {
        var notify = this.notifyList && this.notifyList[id];
        notify && notify.close();
      },
      filteredCameraList: function (option) {
        var size = option.pageSize;
        return option.list.slice((option.currentPage - 1) * size, option.currentPage * size);
      },
      getBoundaryData: function () {
        var vm = this;
        return new Promise((resolve, reject) => {
          vm.$http('./static/json/mapJSON.json').then(function (res) {
            if (res.data) {
              resolve(res.data);
            } else {
              console.error(`获取边界失败`);
              reject(new Error());
            }
          });
        });
      },
      showKqInfo: function (tab) {
        this.ssdtChartTab = tab;
        // if (tab == 'wgy') {
        //   this.initKqInfo(this.kqInfo.wgy);
        // } else {
        //   this.initKqInfo(this.kqInfo.zfdy, 'Zfdy');
        // }
      },
      generateNodes: function () {
        var result = [];
        var map = this.map;
        boundaryData.features.forEach((feature, index) => {
          var rs = {};
          var points = map.getRandomPoint(feature.geometry.coordinates[0]);
          rs = {id: feature.id, points, children: []};
          feature.features.forEach((gird, no) => {
            let ps = map.getRandomPoint(gird.geometry.coordinates[0]);
            rs.children.push({id: gird.id, ps});
          });
          result.push(rs);
        });
        console.log(JSON.stringify(result));
      },
      initKqInfo: function (source, name) {
        // chart
        document.getElementById('chartJrkq' + (name || '')).innerHTML = '';
        var data = [
          {
            item: '在岗',
            percent: source.zc
          }, {
            item: '请假',
            percent: source.qq
          }, {
            item: '未打卡',
            percent: source.yc
          }];
        var chart = new G2.Chart({
          container: 'chartJrkq' + (name || ''),
          width: 280,
          height: 200,
          padding: [10, 90, 10, 10]
        });
        chart.source(data, {
          percent: {
            formatter: function formatter (val) {
              val = val + '%';
              return val;
            }
          }
        });
        chart.coord('theta', {
          radius: 0.82,
          innerRadius: 0.62
        });
        chart.tooltip({
          showTitle: false,
          itemTpl: `<li><span style="background-color:{color};" class="g2-tooltip-marker"></span>{name}: {value}</li>`,
          style: {
            fontSize: 16
          }
        });
        chart.intervalStack().position('percent').color('item').tooltip('item*percent', function (item, percent, count) {
          percent = percent + '%';
          return {
            name: item,
            value: percent
          };
        });
        chart.legend({
          useHtml: true,
          position: 'right',
          containerTpl: '<div class="g2-legend">' +
            '<table class="g2-legend-list" style="list-style-type:none;margin:0;padding:0;"></table>' +
            '</div>'
        });
        chart.render();
      },
      getKqInfo: function () {
        var vm = this;
        vm.getAndLoad('考勤和统计信息', 'api/v3/zhdd/getTodayStat.jsp', function (data) {
          vm.initKqInfo(data.duty);
          vm.tjInfo = data;
        });
      },
      handlerRltbtnClick: function () {
        this.showRlt = !this.showRlt;
        if (this.showRlt) {
          this.rltObject = this.map.showHeatOverLay();
        } else {
          this.rltObject && this.rltObject.hide();
        }
      },
      getTongjiData: function () {
        var vm = this;
        vm.getAndLoad('网格员统计', 'api/other/sy/getSjNum.jsp?spaceId=' + vm.spaceId, function (data) {
          vm.tongjiInfo.wgy = data;
        });
        vm.getAndLoad('执法员统计', 'api/other/zhdd/getZfCaseNum.jsp?spaceId=' + vm.spaceId, function (data) {
          vm.tongjiInfo.zfy = data;
        });
      }
    },
    mounted: function () {
      var vm = this;
      vm.$db.set('userId', vm.userId);
      vm.$db.set('spaceId', vm.spaceId);
      vm.$http((process.env.NODE_ENV == "production" ? '/' : '') + 'api/yth/homePage/city_area.jsp?userId=' + vm.userId).then(function (res) {
        var data = res.data.data;
        vm.topSpaceId = res.data.topSpaceId;
        !vm.spaceId && (vm.spaceId = vm.topSpaceId);
        vm.topSpaceId = res.data.topSpaceId;
        vm.topSpaceName = res.data.topSpaceName;
        if (data) {
          vm.towns.push({
            active: false,
            spaceId: res.data.thisSpaceId,
            spaceName: res.data.thisSpaceName
          });
          vm.currentAreaName = vm.topSpaceName;
          data.forEach(n => {
            n.active = n.spaceId == vm.spaceId;
            n.active && vm.spaceId && (vm.currentAreaName = n.spaceName);
            vm.towns.push(n);
          });
        } else {
          vm.towns.push({
            active: true,
            spaceId: res.data.thisSpaceId,
            spaceName: res.data.thisSpaceName
          });
          vm.userCode = 2;
          vm.spaceId = res.data.thisSpaceId;
          vm.currentAreaName = res.data.thisSpaceName;
        }

        Promise.all([vm.initMap(), vm.getBoundaryData()]).then(function (dataList) {
          boundaryData = dataList[1];
          // vm.initMap().then(() => {
          vm.map.addControlBar(['calc(100vw - 710px)', '100px']);
          // 加网格块
          vm.addFeatures();
          vm.getAndLoad('人员列表', 'api/yth/zhdd/queryPersonLoc.jsp?pageSize=7&pageNo=1&type=all&spaceId=' + vm.spaceId, function (data) {
            data.list.forEach((n) => { n.active = false; });
            vm.ryList = data.list;
            // vm.ryList.length && vm.showRenyanDetail(vm.ryList[0].id);
            if (vm.currentActiveOptionIndex == 4) {
              vm.showMarkers(4);
            }
            vm.optionList[4].loading = false;
            vm.optionList[4].isFirstPage = data.isFirstPage;
            vm.optionList[4].isLastPage = data.isLastPage;
          });
          vm.getAndLoad('事件列表', 'api/other/zhdd/getSjList.jsp?status=待处理&pageSize=6&spaceId=' + vm.spaceId, function (data) {
            data.list.forEach((n, i) => {
              n.active = false;
            });
            vm.optionList[0].isLastPage = data.isLastPage;
            vm.sjList = data.list;
            if (vm.currentActiveOptionIndex == 0) {
              vm.showMarkers(0);
            }
          });
          vm.getTongjiData();
          // vm.getAndLoad('代办事件', 'api/yth/zhdd/queryDoEvents.jsp', function (data) {
          //   vm.dbList = data;
          //   if (vm.currentActiveOptionIndex == 0) {
          //     vm.showMarkers(0);
          //   }
          // });
          setTimeout(function () {
            var compass = document.getElementsByClassName('amap-compass')[0];
            compass && compass.addEventListener('click', function () {
              if (compass.style.transform.includes('rotateX(-0deg)') || compass.style.transform.includes('rotateX(0deg)')) {
                if (vm.rotationAndPitch) {
                  vm.map.setRotationAndPitch(vm.rotationAndPitch.rotation, vm.rotationAndPitch.pitch);
                }
              } else {
                vm.rotationAndPitch = vm.map.getRotationAndPitch();
              }
            });
          }, 2000);
        });
      });
      global.$map = vm;
      layui.use(['layer'], function () {
        window.layer = layui.layer;
      });
      // vm.getKqInfo();
      vm.getAndLoad('网格编号', 'api/v1/wgh/getGrids.jsp', function (data) {
        vm.gridNoArr = data;
      });
      vm.getAndLoad('人员分类', 'api/v1/zhdd/getLocationDepts.jsp', function (data) {
        vm.locationDepts = data;
      });
      window.addEventListener('message', this.handleMessage);
    },
    computed: {
      computedImgs: function () {
        return this.sjInfo.base.imgs.map(n => n.url);
      },
      mapOffset: function () {
        return [0, 0];
      },
      mapCenter: function () {
        return this.$Config.ZHDD_MAP_CENTER;
      },
      leijiNumByGroup: function () {
        var val = this.leijiNum[0];
        if (!val) {
          val = 0;
        }
        var str = (Array(9).join("0") + val).slice(-9);
        return _.chunk(str, 3);
      }
    },
    watch: {
      activePerson: function (n, o) {
        var marker;
        if (n && o && n.id != o.id) {
          marker = this.map.mapBox['Person' + o.id];
          marker && this.map.removeAnimation(marker);
        }
      }
    },
    destroyed: function () {
    }
  };
</script>

<style lang="scss">
@import '../assets/css/zhdd.css';
button[disabled] {
  pointer-events: none;
  cursor: not-allowed;
  filter: alpha(opacity=65);
  -webkit-box-shadow: none;
  box-shadow: none;
  opacity: .65;
}
.nav {
  position: absolute;
  top: 100px;
  left: 90px;
  z-index: 9999;
  width: 600px;
  height:506px;
//  overflow: hidden;
  .home {
      position: absolute;
      bottom: 15px;
      left: 40px;
  }
  .exit {
      position: absolute;
      bottom: 15px;
      right: 40px;
      cursor: pointer;
  }
}
#map-container {
  width: 100%;
  height: 100%;
  &.hideCameras {
    .amap-controlbar {
      left: 1250px !important
    }
  }
  .amap-luopan, .amap-luopan-bg {
    background: url(../assets/imgs/map/a33f94.png) 11px 16px no-repeat !important;
  }
  .amap-compass {
    width: 94px !important;
    background: url(../assets/imgs/map/d1b1de.png) 7px 8px no-repeat !important;
  }
  .amap-pointers {
    display: none;
  }
  .amap-pitchUp {
    cursor: pointer;
    background: url(../assets/imgs/map/d8a900.png) 23px 24px no-repeat !important;
    &.amap-pitch-active {
      background: url(../assets/imgs/map/f23025.png) 23px 24px no-repeat !important;
    }
  }
  .amap-pitchDown {
    cursor: pointer;
    background: url(../assets/imgs/map/d8a900.png) 25px 25px no-repeat !important;
    &.amap-pitch-active {
      background: url(../assets/imgs/map/f23025.png) 25px 25px no-repeat !important;
    }
  }
  .amap-rotateLeft, .amap-rotateRight {
    cursor: pointer;
    background: url(../assets/imgs/map/a3dafe.png) 23px 31px no-repeat !important;
  }
  .amap-rotate-active {
    background: url(../assets/imgs/map/721db7.png) 23px 31px no-repeat !important;
  }
  .playBox-show .amap-controlbar {
    bottom: 170px !important;
  }
  .amap-controlbar-zoom-bg {
    display: none;
  }
  .amap-controlbar-zoom {
    box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.31);
    position: relative;
    width: 72px;
    height: 140px;
    border-radius: 5px;
    background: rgba(39, 39, 39, 0.8) !important;
  }
  .amap-controlbar-zoom-add, .amap-controlbar-zoom-sub {
    position: absolute;
    width: 72px;
    height: 70px;
    margin: 0;
  }
  .amap-controlbar-zoom-add {
    position: relative;
    top: -4px;
    left: 0;
    height: 76px;
    &:after {
      content: "";
      position: absolute;
      width: 56px;
      height: 1px;
      background: #979797;
      left: 7px;
      top: 76px;
    }
  }
  .amap-controlbar-zoom-sub {
    top: 82px;
    left: 2px;
  }
  .amap-marker-label {
    color: white;
    border: none;
    background: none;
    font-size: 20px;
  }
}
.camera-dialog {
  >.el-dialog {
    width: 900px;
  }
  .el-dialog__body {
    padding: 0;
    height: 660px;
    width: 100%;
    iframe {
      width: 100%;
      height: 100%;
      border: none;
    }
  }
}
.camera-popover {
  left: 1700px;
  top: 180px;
  height: 700px;
  .clsBtn {
    width: 55px;
    height: 55px;
    background: url(/static/imgs/cls.png);
    margin: 0 auto;
    position: absolute;
    bottom: 20px;
    left: 0;
    right: 0;
    cursor: pointer;
  }
}
ul.el-cascader-menu {
  height: 300px;
}
#chartJrkq,#chartJrkqZfdy {
  .g2-legend {
    font-size: 22px !important;
    color: white !important;
    top: 10px !important;
    left: 180px !important;
    overflow: hidden !important;
    max-width: unset !important;
    .g2-legend-list {
      display: left;
      flex-wrap: wrap;
      width: 100px;
      height: 300px;
      overflow: hidden;
      .g2-legend-list-item {
        line-height: 55px;
        margin-right: 0 !important;
        text-align: left;
        .g2-legend-marker {
          width: 6px !important;
          height: 16px !important;
          border-radius: 0 !important;
        }
        .g2-legend-text {
          color: white;
          margin-left: 5px;
        }
      }
    }
  }
}

@keyframes fadeInUp2{
  0%{height: 0;}
  to{height: 100%;}
}
.fadeInUp2{
  animation:fadeInUp2 100ms;
}
.bhheight .layui-layer-content >iframe {
  height: 760px !important;
}
</style>
